dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("esri.graphic");
dojo.require("esri.layers.agstiled");
dojo.require("esri.toolbars.draw");
dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("esri.undoManager");
dojo.provide("myModules.customoperation");
dojo.require("esri.tasks.geometry");
var mymap,toolbar,reExtent,dotList,undoManager,resizeTimer,componentType,geometryService;
var s = "";
var color = {
    storeCell:{
        solidColor:[0,187,255],
        fillColor:[0,187,255,0.25],
        fill_color:[0,187,255,64]
    },
    produceCell:{
        solidColor:[145,197,53],
        fillColor:[145,197,53,0.25],
        fill_color:[145,197,53,64]
    },
    wasteProduce:{
        solidColor:[254,236,36],
        fillColor:[254,236,36,0.25],
        fill_color:[254,236,36,64]
    },
    solidWaste:{
        solidColor:[208,0,253],
        fillColor:[208,0,253,0.25],
        fill_color:[208,0,253,64]
    },
    waterWaste:{
        solidColor:[0,172,191],
        fillColor:[0,172,191,0.25],
        fill_color:[0,172,191,64]
    },
    gasWaste:{
        solidColor:[255,100,0],
        fillColor:[255,100,0,0.25],
        fill_color:[255,100,0,64]
    }
}
//撤销 重做 申明
dojo.declare("myModules.customoperation.Add", esri.OperationBase, {
    label: "Add Graphic",
    constructor: function ( /*graphicsLayer, addedGraphic*/ params) {
        params = params || {};
        if (!params.graphicsLayer) {
            console.error("graphicsLayer is not provided");
            return;
        }
        this.graphicsLayer = params.graphicsLayer;

        if (!params.addedGraphic) {
            console.error("no graphics provided");
            return;
        }
        this._addedGraphic = params.addedGraphic;
    },

    performUndo: function () {
        this.graphicsLayer.remove(this._addedGraphic);
    },

    performRedo: function () {
        this.graphicsLayer.add(this._addedGraphic);
    }
});

function init(){
    mymap = new esri.Map("map",{logo:false,autoResize:true});
    var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer
        ("http://61.155.4.230:12580/arcgis/rest/services/iMap_/iMap/MapServer"); //加载动态地图
    mymap.addLayer(dynamicMapServiceLayer);
    mymap.resize();
    mymap.reposition();
    dojo.connect(mymap, 'onLoad', function(theMap) {
        dojo.connect(dijit.byId('map'), 'resize', map,map.resize);
        var name = $('#name').val();
        drawEndEvent(name);
    });
    dojo.connect(mymap, "onExtentChange", showExtent);
    dojo.connect(mymap,'onLoad',function(){
        var type = $('#name').val();
        loadCompanyRange();
        loadGeoData(type);
    });
}
dojo.addOnLoad(init);

//加载企业边界
function loadCompanyRange(){
    _geo_points = eval(geo_points);
    var solidColor = [254,236,36],
        fillColor = [102,255,51,255],
        fill_color = [255,255,255,0];
    var rangePolygon = {
        "geometry":{
            "rings":[_geo_points],
            "spatialReference": { "wkid": 102100 }
        },
        "symbol":{
            "color":fill_color,
            "outline":{
                "color":fillColor,
                "width":2,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        }
    };

    var gra = new esri.Graphic(rangePolygon);
    mymap.graphics.add(gra);
}

function showExtent(extent) {
    s = "XMin: "+ extent.xmin + "&nbsp;"
        +"YMin: " + extent.ymin + "&nbsp;"
        +"XMax: " + extent.xmax + "&nbsp;"
        +"YMax: " + extent.ymax;
}

function drawEndEvent(name){
    toolbar = new esri.toolbars.Draw(mymap);
    dojo.connect(toolbar, "onDrawEnd", function(geometry){
        toolbar.deactivate();
        var symbol;
        if(name == 'sensor' || name == 'sensitive'||name=='savepoint'){
            // 添加点操作
            var ico = {
                'sensitive':'/static/images/sensitive.png',
                'sensor':'/static/images/sensor.png',
                'savepoint':'/static/images/savepoint.png'
            }
            symbol = new esri.symbol.PictureMarkerSymbol(ico[name], 26, 26);
        }else if(name == 'truck' || name == 'ship'||name=='pipe'){
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,186,207]), 3);
        }else{
            // 添加区域操作
            symbol = new esri.symbol.SimpleFillSymbol(
                esri.symbol.SimpleFillSymbol.STYLE_SOLID,
                new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                    new dojo.Color(color.storeCell.solidColor), 2),
                new dojo.Color(color.storeCell.fillColor)
            );
        }
        var graphic = new esri.Graphic(geometry, symbol);
        var operation = new myModules.customoperation.Add({
            graphicsLayer: mymap.graphics,
            addedGraphic: graphic
        });
        undoManager.add(operation);
        mymap.graphics.add(graphic);
        var dotList;
        if(name == 'sensor' || name == 'sensitive'||name=='savepoint'){
            values = '['+ graphic.geometry.x +','+ graphic.geometry.y +']';
            var center = values
        }else if(name == 'truck' || name == 'ship'||name=='pipe'){
            values = JSON.stringify(graphic.geometry.paths[0]);
            var centerPoint=graphic.geometry.getExtent().getCenter();
            var center = "["+centerPoint.x +","+centerPoint.y +"]"
        }
        else{
            values = JSON.stringify(graphic.geometry.rings[0]);
            var centerPoint=graphic.geometry.getExtent().getCenter();
            var center = "["+centerPoint.x +","+centerPoint.y +"]"
        }
           //给赋地图值
        $('#center').val(center);
        $('#valuePolygon').val(values);
    });
}

function drowPolygon(name){   //'store'
    toolbar.activate(esri.toolbars.Draw.POLYGON);   //可以画多边形了
    //携带，一个参数
    var info="";
    switch(name){
        case "store":
            info = "开始绘制存储单元边界";
            break;
        case "produce":
            info = "开始绘制生产单元边界";
            break;
        case "wasteOutput":
            info = "开始绘制废物产生量边界";
            break;
        case "dangerSolidWaste":
            info = "开始绘制危险固废产生和排放边界";
            break;
        case "wasteWater":
            info = "开始绘制废水污染物产生和排放量边界";
            break;
        case "wasteGas":
            info = "开始绘制废气污染物产生和排放量边界";
            break;
        case "sensitive":
            toolbar.activate(esri.toolbars.Draw.POINT); 
            info = "开始绘制敏感点";
            break;
        case "sensor":
            toolbar.activate(esri.toolbars.Draw.POINT); 
            info = "开始绘制传感器";
            break;
        case "savepoint":
            toolbar.activate(esri.toolbars.Draw.POINT); 
            info = "开始绘制应急物资存放点";
            break;
        case "ship":
            toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYLINE); //连续线条
            info = "开始绘制船运路线";
            break;
        case "truck":
            toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYLINE); //连续线条
            info = "开始绘制车运路线";
            break;
        case "pipe":
            toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYLINE); //连续线条
            info = "开始绘制管道路线";
            break;
    }
    infoPop(info);
}

function infoPop(info){
    $("#toast-container").remove();
    var opts = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "2000",
        "extendedTimeOut": "5000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    toastr.info("", info, opts);
}

function toSubmitModal(title,content,type){     // storeCell  storage的内容    开始赋值呈现
    $('#rangeModal').modal({show:true});
    $('#rangeModal #content').empty().append(content);
    $("#rangeModal #title").empty().append(title);

    $("#rangeModal #submit").bind('click',function(){
        submitData();
    });
}

function submitData(){
    var doList = $('#valuePolygon').val();
    var center = $('#center').val();
    var arrValue = $('#ids').val().split(',');
    $.ajax({
        url:$.showMapObj.options.dataSubmitURL,
        data:{
            ids:JSON.stringify(arrValue),    //某个storage的id   种类已经知道了
            points:doList, //地图信息
            center:center
        },
        type:'POST',
        dataType:'json',
        success:function(data){
            if(data.success){
                alert(data.success);
                window.location.reload();
            }
            if(data.error){
                alert(data.error);
            }
        }
    })

}
//加载区域
function loadGeoData(type){
    var _mapData = $.showMapObj.data.map;

    var border_color=color.storeCell.solidColor;
    var fill_color=color.storeCell.fill_color;
        border_color.push(255);
        fill_color.splice(3);
        fill_color.push(64);
    if(! _mapData )    return false;

    for(var i = 0; i < _mapData.length; i++){

        console.log(_mapData[i])

        var _tmpInfo = $("#mapPopHideArea").clone();
        var _item  = _mapData[i];
        var _header = _item.header.split(',');
        var _points = JSON.parse(_item.group.points);

        var _length = _item.data.length;
        var _title = _item.title;
        if(_length == 0){
            _tmpInfo.html('暂无数据');
        }else{
            for(var ii=0; ii<_header.length; ii++){
                var _th = '<th>'+ _header[ii] +'</th>'

                _tmpInfo.find("#_headTr").append( _th );
            }

            for(var j = 0; j < _length; j++){
                var _tr = '<tr>';

                for(var k=0; k< $.showMapObj.data.dataStructure.length; k++){
                    var key = $.showMapObj.data.dataStructure[k];
                    _tr+= '<td>'+ _item.data[j][key] +'</td>';
                }

                _tr+= '</tr>';

                _tmpInfo.find("table tbody").append(_tr);
            }
        }

        var _context= _tmpInfo.html();

        if(type == 'sensitive' || type == 'sensor'||type == 'savepoint'){

            var ico = {
                'sensitive':'/static/images/sensitive.png',
                'sensor':'/static/images/sensor.png',
                'savepoint':'/static/images/savepoint.png'
            }

            var myPoint =  {
                "geometry":{
                    "x":_points[0],
                    "y":_points[1],
                    "spatialReference":{
                        "wkid":4326
                    }
                },
                "attributes":{
                    "XCoord":-104.4140625,
                    "YCoord":69.2578125,
                    "Plant":"Mesa Mint"
                },
                "symbol":{
                    "url":ico[type],
                    "height":20,
                    "width":20,
                    "type":"esriPMS"
                },
                "infoTemplate":{
                   "title":_title,
                   "content":"<div>"+ _context +"</div>"
                }
            };

            var pictureMarkerSymbol = new esri.symbol.PictureMarkerSymbol('/static/images/sensor.png', 20, 20);
            var graphicPic = new esri.Graphic(myPoint);  
                // graphicPic.attributes = { name:options.name };
            mymap.graphics.add(graphicPic);

      }else if(type == 'truck' || type == 'ship'||type=='pipe'){

            var myPolygon = {
                "geometry":{
                    "paths":[_points],
                    "spatialReference": {
                        "wkid": 102100
                    }
                },
                "symbol":{
                    "color":[0,187,255,255],
                    "width":3,
                    "type":"esriSLS",
                    "style":"esriSLSSolid"
                },
                "infoTemplate":{
                    "title":_title,
                    "content":"<div>"+ _context +"</div>"
                }
            };

            mymap.infoWindow.resize(260,120);
            var gra = new esri.Graphic(myPolygon);
            mymap.graphics.add(gra);
       }else{
            var myPolygon = {
                "geometry":{
                    "rings":[_points],
                    "spatialReference": {
                        "wkid": 102100
                    }
                },
                "symbol":{
                    "color":fill_color,
                    "outline":{
                        "color":border_color,
                        "width":2,
                        "type":"esriSLS",
                        "style":"esriSLSSolid"
                    },
                    "type":"esriSFS",
                    "style":"esriSFSSolid"
                },
                "infoTemplate":{
                    "title": _title,
                    "content":"<div>"+ _context +"</div>"
                }
            };

            mymap.infoWindow.resize(260,120);
            var gra = new esri.Graphic(myPolygon);
            mymap.graphics.add(gra);
        }
    }
}

